/*
 * This is the Demo Launcher
 */
package SocketDemo;

public class App {
    public static void main(String[] args) throws InterruptedException {
        int interval = 3000;
        boolean isClient = false;
        String usage = 
            "Usage: java SocketDemo.App <server|client> [host] [port]\n" +
            "       server: run app whith server mode, this mode will listen on port and host address.\n" +
            "       client: run app whith client mode, this mode will connect to server with host and port.\n" +
            "       host: hostname or IP address. default: localhost.\n" +
            "       port: port number. default: 8887.";

        String host = "localhost";
        int port = 8887;

        if (args.length < 1) {
            System.out.println(usage);
            System.exit(0);
        }

        switch(args[0]) {
            case "server":
                isClient = false;
                break;
            case "client":
                isClient = true;
                break;
            default:
                System.out.println(usage);
                System.exit(0);
        }

        if (args.length == 2) {
            port = Integer.parseInt(args[1]);
        } else if (args.length == 3) {
            host = args[1];
            port = Integer.parseInt(args[2]);
        } else if (args.length > 3) {
            System.out.println(usage);
            System.exit(0);
        }

        if (isClient) {
            while (true) {
                try {
                    Client client = new Client(host, port);
                    client.send("Hi, I'm Client");
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    Thread.sleep(interval);
                }
            }
        } else {
            Server server = new Server(port);
            server.start();
        }
    }
}
